<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.Code"
        placeholder="门店代码"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-input
        v-model="listQuery.JxsName"
        placeholder="经销商姓名"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-input
        v-model="listQuery.JxsPhone"
        placeholder="经销商电话"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-input
        v-model="listQuery.Gd"
        placeholder="跟单名字"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />

      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        查询
      </el-button>
      <el-button

        class="filter-item"
        type="primary"
        icon="el-icon-plus"
        @click="toAddMdpage"
      >
        去添加门店
      </el-button>
      <el-checkbox
        v-model="showReviewer"
        class="filter-item"
        style="margin-left: 15px;"
        @change="tableKey = tableKey + 1"
      >
        reviewer
      </el-checkbox>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <!-- <el-table-column
        label="ID"
        prop="id"
        sortable="custom"
        align="center"
        width="80"
        :class-name="getSortClass('id')"
      >
        <template slot-scope="{ row }">
          <span>{{ row.Id }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="代码" width="80px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.Code }}</span>
        </template>
      </el-table-column>

      <el-table-column label="我的标记名称" width="220px">
        <!-- <template slot-scope="{ row }">
          <span>{{ row.TagName }}</span>
          <span style="color: red; font-size: 10px; cursor: pointer">修改</span>
        </template> -->

        <template slot-scope="{ row }">
          <template v-if="row.edit">
            <el-input
              v-model="row.TagName"
              class="edit-input"
              size="mini"
              style="max-widtha: 140px; margin-right: 5px;"
            />
            <el-button
              class="cancel-btn"
              size="mini"
              icon="el-icon-refresh"
              type="warning"
              @click="cancelEdit(row)"
            >
              取消
            </el-button>
          </template>
          <span v-else style="margin-right: 5px;">{{ row.TagName }}</span>
          <!-- --------------------------------------------------- -->
          <el-button
            v-if="row.edit"
            type="success"
            size="mini"
            icon="el-icon-circle-check-outline"
            @click="confirmEdit(row)"
          >
            更新
          </el-button>
          <el-button
            v-else
            type="default"
            size="mini"
            icon="el-icon-edit"
            @click="row.edit = !row.edit"
          ></el-button>
        </template>
      </el-table-column>

      <el-table-column label="经销商" width="100px">
        <template slot-scope="{ row }">
          <span class="link-type" @click="handleUpdate(row)">
            {{ row.JxsName }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="经销商电话" width="180px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.JxsPhone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="代理品牌" width="180px" align="center">
        <template slot-scope="{ row }">
          <div v-if="row.Brands.length > 0">
              <span v-for="brand in row.Brands" :key="brand.Id">{{ brand.Name}}，</span>
          </div>
          <div v-else>
            <span>暂无代理品牌</span>
          </div>
          
        </template>
      </el-table-column>
      <el-table-column
        v-if="showReviewer"
        label="Reviewer"
        width="110px"
        align="center"
      >
        <template slot-scope="{ row }">
          <span style="color: red;">{{ row.reviewer }}</span>
        </template>
      </el-table-column>

      <!-- <el-table-column label="代理品牌" align="center" width="95">
        <template slot-scope="{ row }"> </template>
      </el-table-column> -->
      <el-table-column label="责任跟单" class-name="status-col" width="100">
        <template slot-scope="{ row }">
          {{ row.Gd }}
        </template>
      </el-table-column>
      <el-table-column
        label="可用(冻结)余额"
        class-name="status-col"
        width="160"
      >
        <template slot-scope="{ row }">
          {{ row.Price }}
          <span style="font-size: 10px; color: red;">
            ({{ row.FreezingPrice }})
          </span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="充值" width="80px" align="center">
        <template slot-scope="{ row }">
          <el-button
            size="mini"
            @click="handleUpdateAdRecharge(row)"
            type="default"
          >
            充值
          </el-button>
        </template>
      </el-table-column> -->
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        style="display:flex:flex-wrap:wrap; "
      >
        <template slot-scope="{ row }">
          <el-button type="primary" plain   size="mini" @click="handleAddGoods(row)" style="margin:0 10px 10px 0">
            添加商品
          </el-button>
          <el-button type="primary" plain   size="mini" @click="handleUpdateAdRecharge(row)" style="margin:0 10px 10px 0">
            充值
          </el-button>
          <el-button type="primary" plain  size="mini" @click="handleActive(row)" style="margin:0 10px 10px 0">
            查看活动
          </el-button>

          <!-- <el-button
            v-if="row.status != 'published'"
            size="mini"
            type="success"
            @click="handleModifyStatus(row, 'published')"
          >
            广告详情
          </el-button> -->
          <!-- <el-button
            v-if="row.status != 'published'"
            size="mini"
            type="success"
            @click="adpage(row, 'published')"
          >
            创建落地页
          </el-button> -->
          <el-button
            v-if="row.status != 'published'"
            size="mini" plain
            type="primary"
            style="margin:0 10px 10px 0"
            @click="addBrand(row, 'published')"
          >
            添加品牌
          </el-button>
          <el-button
            v-if="row.status != 'published'"
            size="mini" plain
           type="primary"
           style="margin:0 10px 10px 0"
            @click="filterProduct(row, 'published')"
          >
            公司产品筛选
          </el-button>
          <el-button
            v-if="row.status != 'published'"
            size="mini" plain
            type="primary"
            style="margin:0 10px 10px 0"
            @click="addad(row, 'published')"
          >
            投放广告
          </el-button>
          <el-button
            v-if="row.status != 'published'"
            size="mini" plain
           type="primary"
           style="margin:0 10px 10px 0"
            @click="adlist(row, 'published')"
          >
            门店广告
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <!-- ------------------------- -->
    <el-dialog :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="70px"
        style="width: 400px; margin-left: 50px;"
      >
        <el-form-item label="店名称" prop="TagName">
          <el-input v-model="temp.TagName" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
          修改
        </el-button>
      </div>
    </el-dialog>
    <!-- ======================= -->
    <el-dialog :visible.sync="dialogFormAdRecharge">
      <el-form
        ref="dataFormad"
        :rules="rulesad"
        :model="tempad"
        label-position="left"
        label-width="90px"
        style="width: 300px; margin-left: 50px;"
      >
        <el-form-item label="充值金额" prop="AddPrice">
          <el-input v-model="tempad.AddPrice" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormAdRecharge = false">取消</el-button>
        <el-button type="primary" @click="updateDataad()">提交</el-button>
      </div>
    </el-dialog>
    <!-- ======================= -->
    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table border fit highlight-current-row style="width: 100%;">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">
          Confirm
        </el-button>
      </span>
    </el-dialog>

    <!-- 公司产品筛选弹出层 -->
    <el-dialog :visible.sync="dialogProductVisible" title="CBD家居产品">
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogProductVisible = false">
          确定
        </el-button>
      </span>
    </el-dialog>

    <!-- 品牌添加 -->
    <el-dialog :visible.sync="dialogBrandVisible" title="添加品牌">
      <div class="brand-list">
        <div class="brand" v-for="item in MdBrand" :key="item.Id" @click="handleSelectBrand(item.Id)">
          <button
            :class="item.Selected ? 'active' : 'brand-btn'"
            :disabled="item.Self"
          >
            {{ item.Name }}
          </button>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="chooseBrand">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  fetchList,
  tagMdName,
  adRecharge,
  chooseHeadProduct,
  addMdBrand,
  updateMdBrand,
} from '@/api/mdlist'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination


const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' },
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger',
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    },
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        my: '1',
        page: 1,
        limit: 10,
        importance: undefined,
        title: undefined,
        type: undefined,
        sort: '+id',
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [
        { label: 'ID Ascending', key: '+id' },
        { label: 'ID Descending', key: '-id' },
      ],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      // ======================================================
      temp: {
        id: undefined,
        TagName: '',
      },
      dialogFormVisible: false,
      dialogStatus: '',

      dialogPvVisible: false,
      rules: {
        TagName: [
          { required: true, message: '店名称不可为空', trigger: 'blur' },
        ],
      },
      // ---------------------------------
      tempad: {
        id: undefined,
        AddPrice: '',
      },
      dialogFormVisible: false,
      dialogStatus: '',

      dialogPvVisible: false,
      rulesad: {
        AddPrice: [
          { required: true, message: '金额不可为空', trigger: 'blur' },
        ],
      },
      // ---------------------------------
      downloadLoading: false,
      dialogFormAdRecharge: false,
      dialogBrandVisible: false, //品牌添加弹出层
      dialogProductVisible: false, //公司产品弹出层
      MdBrand: [], //门店的选择的品牌
      Mdid: '', //门店Id
    }
  },
  created() {
    this.getList()
  },
  methods: {
    cancelEdit(row) {
      row.TagName = row.originalTitle
      row.edit = false
      this.$message({
        message: 'The title has been restored to the original value',
        type: 'warning',
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdateAdRecharge(row) {
      this.tempad = Object.assign({}, row) // copy obj
      this.dialogFormAdRecharge = true
      this.$nextTick(() => {
        this.$refs['dataFormad'].clearValidate()
      })
    },
    handleAddGoods(row){
      this.$router.push({ name: 'goodsdetail',query: { mdid: row.Id} })
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery)
        .then((response) => {
          this.list = response.data.items.map((v) => {
            this.$set(v, "edit", false) // https://vuejs.org/v2/guide/reactivity.html
            v.originalTitle = v.TagName //  will be used when user click the cancel botton
            return v
          })

          this.total = response.data.total

          // Just to simulate the time of the request
          // this.listLoading = false;
          setTimeout(() => {
            this.listLoading = false
          }, 100)
        })
        .catch(function () {
          console.log('aaaaaaaaaaaa9999999999999')
        })
    },
    confirmEdit(row) {
      tagMdName({ TagName: row.TagName }, { Mdid: row.Id }).then((response) => {
        row.edit = false
        this.listLoading = false
        if (response.code == 0) {
          row.originalTitle = row.TagName
          this.dialogFormVisible = false
          this.$message({
            message: 'The title has been edited',
            type: 'success',
          })
          this.getList()
        }
      })
    },

    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success',
      })
      row.status = status
    },
    adpage(row, status) {
      // console.log(row, "aaaaaaaaaaaaaaaaaaaaaa");
      this.$router.push({ name: 'cbd-adpage', query: { id: row.Id } })
    },
    addad(row, status) {
      // console.log(row, "aaaaaaaaaaaaaaaaaaaaaa");
      this.$router.push({ name: 'cbd-addad', query: { id: row.Id } })
    },
    adlist(row, status) {
      // console.log(row, "aaaaaaaaaaaaaaaaaaaaaa");
      this.$router.push({ name: 'cbd-adlist', query: { id: row.Id } })
    },

    //公司产品筛选
    filterProduct(row, status) {
      this.dialogProductVisible = true
      chooseHeadProduct({ Mdid: row.Id }).then((res) => {
        console.log(res)
      })
    },

    //获取公司品牌
    addBrand(row) {
      this.Mdid = row.Id
      this.dialogBrandVisible = true
      addMdBrand({ Mdid: row.Id }).then((res) => {
        if (res.msg === 'success') {
          console.log(res.data.list,'sssssssss')
          this.MdBrand = res.data.list
        }
      })
    },

    //选择品牌
    handleSelectBrand(BrandId) {
      for (let i = 0; i < this.MdBrand.length; i++) {
        if (this.MdBrand[i].Id === BrandId) {
          this.MdBrand[i].Selected = !this.MdBrand[i].Selected
        }
      }
    },

    //提交选择的品牌
    chooseBrand() {
      let BrandIdList = []
      for (let i = 0; i < this.MdBrand.length; i++) {
        if (this.MdBrand[i].Selected) {
          BrandIdList.push(this.MdBrand[i].Id)
        }
      }
      if (BrandIdList.length > 0) {
        updateMdBrand({ Mdid: this.Mdid }, { Brands: BrandIdList }).then(
          (res) => {
            if (res.msg === 'success') {
              alert('选择成功！')
              this.dialogBrandVisible = false
               this.getList()
            }
          },
        )
      }
    },

    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        status: 'published',
        type: '',
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          this.temp.author = 'vue-element-admin'
          createArticle(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000,
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)

          tagMdName({ TagName: tempData.TagName }, { Mdid: tempData.Id }).then(
            (response) => {
              this.listLoading = false
              if (response.code == 0) {
                this.dialogFormVisible = false
                this.getList()
              }
            },
          )
          // tempData.timestamp = +new Date(tempData.timestamp); // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          // updateArticle(tempData).then(() => {
          //   const index = this.list.findIndex((v) => v.id === this.temp.id);
          //   this.list.splice(index, 1, this.temp);
          //   this.dialogFormVisible = false;
          //   this.$notify({
          //     title: "Success",
          //     message: "Update Successfully",
          //     type: "success",
          //     duration: 2000,
          //   });
          // });
        }
      })
    },
    updateDataad() {
      this.$refs['dataFormad'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.tempad)
          console.log(
            tempData,
            'aaaaaaaaaaaaaaaaaaaaaaaaaa',
            Number(tempData.AddPrice) * 100,
          )

          adRecharge(
            { Price: Number(tempData.AddPrice) * 100 },
            { Mdid: tempData.Id },
          ).then((response) => {
            this.listLoading = false
            if (response.msg == "success") {
              this.$message.success('操作成功');
              this.dialogFormAdRecharge = false
              this.getList()
            }else{
              this.$message.error(response.msg);
            }
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$notify({
        title: 'Success',
        message: 'Delete Successfully',
        type: 'success',
        duration: 2000,
      })
      this.list.splice(index, 1)
    },

    getSortClass: function (key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    toAddMdpage: function () {
      this.$router.push({ name: 'cbd-searchmdlist' })
    },

    handleActive(row){
     this.$router.push({ name: 'cbd-activelist',query: { Mdid: row.Id} })
    }
  },
}
</script>
<style >
.brand-list {
  width: 100%;
  padding: 20px 10px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.brand {
  width: 100px;
  height: 36px;
  text-align: center;
  line-height: 36px;
  margin: 0 10px 10px 0;
}
.brand button {
  width: 100px;
  height: 36px;
  font-size: 14px;
  color: #000;
  text-align: center;
  border-radius: 2px;
}
.active {
  background-color: #e46715;
  border: 1px solid #e46715;
}
.brand-btn {
  background: #f4f4f5;
  border: 1px solid #b9b8b8;
}
</style>
>
